package com.starbaba.system.download.view;

import java.io.InputStream;

import javax.servlet.ServletContext;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.util.ServletContextAware;

import com.opensymphony.xwork2.Action;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.io.IOUtilFactory;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.system.attach.model.AttachVO;

@SuppressWarnings("serial")
public class DownloadAction extends BaseAction implements ServletContextAware {
	
	public static final String DOWNLOAD_STATUS_ERROR = "error";
	public static final String DOWNLOAD_STATUS_SUCCESS = "success";
	
	static final Logger logger = Logger.getLogger(DownloadAction.class);
	/* 原始文件名 */
	private String fileName;
	/* 文件存储位置全名 */
	private String fullFilePath;
	
	private ServletContext context;
	
	@Override
	public String execute() throws Exception {
		try{
			paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
			String attachId = (String) paramsMap.get("attachId");//"131973966682810";
			if(StringUtils.isNotBlank(attachId)){
				AttachVO attachVO = (AttachVO) this.getService().doFindByPk(AttachVO.class, attachId);
				if(null == attachVO){
					this.addErrorMessage("下载附件不存在.");
					return Action.ERROR;
				}
				fileName = attachVO.getFilename();
				fullFilePath = attachVO.getSavepath();
			}else{
				this.addErrorMessage("请求资源不存在或地址不正确.");
				return Action.ERROR;
			}
		}catch(Exception ex){
			ex.printStackTrace();
			this.addErrorMessage(ex.getMessage());
			return Action.ERROR;
		}
        return Action.SUCCESS;
    }
	
	public String getFileName() throws Exception {
		return new String(fileName.getBytes(), "ISO8859-1");
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public InputStream getInputStream() throws Exception {
//		java.io.File downFile = new java.io.File(this.getFullFilePath());
//		return new java.io.FileInputStream(downFile);
		return IOUtilFactory.openInputStream(this.getFullFilePath());
	}
	
	public String getFullFilePath() {
		return fullFilePath;
	}

	public void setFullFilePath(String fullFilePath) {
		this.fullFilePath = fullFilePath;
	}

	@Override
	public void setServletContext(ServletContext context) {
		this.context = context;
	}

	public ServletContext getContext() {
		return context;
	}

	public void setContext(ServletContext context) {
		this.context = context;
	}

}
